#include "pz_model.h"
#include "drv_fpga.h"
extern int cycleTras;
extern uint8 uart_buf[PZ_PL_UART_DLEN];
void Uart422_init();
int Uart_send(uint8 *rbuf, int len);
int Uart_recv(int len, int timeouts);
void send_net_data(uint8 *cbuf, int clen);

int pz_send_data(uint8 *rbuf, int len) {
    Uart_send(rbuf, len);
}

int pz_recv_data(int len) {
    return Uart_recv(len, PZ_TIMEOUT);
}

void pz_del_netdata(uint8 *rbuf) {
    PzPack_DATA pdata;
    memcpy(&pdata, rbuf, sizeof(PzPack_DATA));
    
    // to del pz data
    if(rbuf[1] == 0xA8){
        // 0x00	带宽控制70MHz. 1.08
        // 0x01	带宽控制28MHz. 1.08
        // 0x02	带宽控制14MHz. 2.08
        if(rbuf[2] == 0x02) {            // 14MHZ, 同步时钟周期为 2.08ms
            cycleTras = 208;                                
            LOG_INFO("update cycleTras is 2.08");            
            // send_model(2);
        } else if(rbuf[2] == 0x01) {    //28MHz 到 70MHz， 1.08ms
            cycleTras = 108;
            LOG_INFO("update cycleTras is 1.08");            
            // send_model(1);
        } else if(rbuf[2] == 0x00) {   //70MHz
            cycleTras = 108;
            LOG_INFO("update cycleTras is 1.08");            
            // send_model(0);
        } else {
            LOG_INFO("Bandwidth control error: %d", rbuf[2]);
        }
    }

    printHex1((uint8 *)(&pdata), PZ_PL_UART_DLEN, PZ_PL_UART_DLEN, "uart_422 send:");

    if(pz_send_data((uint8 *)&pdata, sizeof(PzPack_DATA))) { LOG_ERROR("pz data send fail"); return ; };
    
    if(KT_ERROR != pz_recv_data(sizeof(PzPack_DATA))) {
        printHex1(uart_buf, PZ_PL_UART_DLEN, PZ_PL_UART_DLEN, "uart_422 recv:");

        send_net_data(uart_buf, sizeof(PzPack_DATA));
        LOG_INFO("forward PZ data to network successful");
    } else {
        LOG_INFO("Uart recv error");
    }
}

void pz_model_init() {
    Uart422_init();
}
